<template>
  <div class="main-contain">
    <canvas :id="'canvas' + canvasId" width="180" height="180"></canvas>
    <!-- <button @click="abc">点击</button> -->
  </div>
</template>
<script lang="ts" setup>
import { ElMessage, ElMessageBox } from "element-plus";
import type { Action } from "element-plus";
import dayjs from "dayjs";
import { ref, onMounted, nextTick, toRefs, watch, onBeforeMount } from "vue";
const props = defineProps(["canvasId"]);
const { canvasId } = toRefs(props);
const title = ref("");
let speed = 0;
let i = 0;
let timer: any;
let timerWarn: any;
let num = ref<any>(0);
var canvas: HTMLCanvasElement; //获取画布承载容器,不加HTMLCanvasElement会报错
/* 画曲线 */
function drawCircle(ctx: any, config: any) {
  const { x, y, radius, startAngle, endAngle, color, lineWidth, type } = config;
  ctx.beginPath();
  ctx.arc(x, y, radius, startAngle, endAngle, false);
  // 设定曲线粗细度
  ctx.lineWidth = lineWidth;
  if (type == 1) {
    var jb = ctx.createLinearGradient(0, 0, 180, 0);
    jb.addColorStop(0, "rgb(97,186,255)");
    jb.addColorStop(1, "#fff"); //参数为0<stop<1,color
    // 给曲线着色
    ctx.strokeStyle = jb;
  } else {
    // 给曲线着色
    ctx.strokeStyle = color;
  }

  // 连接处样式
  ctx.lineCap = "round";
  // 给环着色
  ctx.stroke();
  ctx.closePath();
}
function circle() {
  const { width, height } = canvas;
  const ctx = canvas.getContext("2d")!; //加上!告诉ts我有信心它不为空
  // // 清除画布
  ctx.clearRect(0, 0, width, height);
  // // 保存
  // ctx.save();
  // ctx.globalAlpha = speed / num.value;
  /* 填充文字 */
  ctx.font = "12px Microsoft YaHei";
  /* 文字颜色 */
  var jb = ctx.createLinearGradient(0, 0, 100, 0);
  jb.addColorStop(0, "rgb(97,186,255)");
  jb.addColorStop(1, "#fff"); //参数为0<stop<1,color
  ctx.fillStyle = jb;
  /* 文字内容 */
  const insertContent = title.value;
  // 拿到文本内容的像素相关信息 单位长度(px)
  const measureText = ctx.measureText(insertContent);
  /* 插入文字，后面两个参数为文字在画布中的坐标点 */
  /* 此处注意：text.width获得文字的宽度，然后就能计算出文字居中需要的x值 */
  ctx.fillText(insertContent, (width - measureText.width) / 2, height / 2 + 30);

  /* 填充百分比 */
  ctx.font = "30px Microsoft YaHei";

  ctx.fillStyle = jb;
  const ratioStr = `${((speed * num.value) / 100).toFixed(0)} %`;
  const text = ctx.measureText(ratioStr);
  ctx.fillText(ratioStr, (width - text.width) / 2, height / 2);

  /* 开始圆环 */
  const circleConfig = {
    /* 圆心坐标 */
    x: width / 2,
    y: height / 2,
    /* 半径，下方出现的150都是半径 */
    radius: width / 2 - 15,
    /* 环的宽度 */
    lineWidth: 24,
    /* 开始的度数-从上一个结束的位置开始 */
    startAngle: 0, // 注意这里的0是3点钟方向，而非12点方向，和数学里的不一样
    /* 结束的度数 */
    endAngle: 360,
    color: "rgb(24,141,240)",
    type: 0,
  };
  /* 灰色的圆环 */
  drawCircle(ctx, circleConfig);
  if (num.value > 0) {
    const circleConfig2 = {
      ...circleConfig,
      startAngle: 0, // 注意这里的0是3点钟方向，而非12点方向，和数学里的不一样
      /* 结束的度数 */
      endAngle: (Math.PI / 180) * 360 * ((speed / 100) * (num.value / 100)),
      color: "green",
      type: 1,
    };
    drawCircle(ctx, circleConfig2);
  }

  timer = window.requestAnimationFrame(() => {
    if (num.value == 0) {
      window.cancelAnimationFrame(timer);
      return;
    }
    //在相同时间内完成一次的进度显示
    if (speed > 100) {
      window.cancelAnimationFrame(timer);
      return;
    }
    // console.log(speed);
    circle();
  });
  speed += 1;
}
watch(num, (newValue, oldValue) => {
  nextTick(() => {
    speed = 0;
    circle();
  });
});
onMounted(() => {
  let class2: string = `#canvas${canvasId?.value}`;
  canvas = document.querySelector(class2)!;
  if (canvasId?.value == "serve") {
    title.value = "服务器内存使用率";
    num.value = Math.ceil(Math.random() * 100);
  } else {
    title.value = "服务器私有消耗率";
    timerWarn = setInterval(() => {
      getExpend();
    });
  }
  circle();
});
onBeforeMount(() => {
  window.cancelAnimationFrame(timer);
  timer = null;
  clearInterval(timerWarn);
  timerWarn = null;
});
function getExpend() {
  let totalLongTime = dayjs("2024-06-03").diff(dayjs("2023-06-03"), "day");
  let timestamp = dayjs("2024-06-03").diff(
    dayjs(dayjs().format("YYYY-MM-DD")),
    "day"
  ); // 时间戳
  // console.log(timestamp)
  if (timestamp <= 0) {
    clearInterval(timerWarn);
    timerWarn = null;
    num.value = 100;
    if (localStorage.getItem("notice")) {
      return;
    }
    ElMessageBox.alert(
      "服务器即将过期停止服务，请联系管理员维护！,qq:1356124239,可加好友可发邮件",
      "紧急警告",
      {
        confirmButtonText: "好的",
        callback: (action: Action) => {
          localStorage.setItem("notice", "1");
          ElMessage({
            type: "info",
            message: `你已@管理员,抓紧时间使用吧~`,
          });
        },
      }
    );
    return;
  }
  num.value = ((1-(timestamp / totalLongTime)) * 100).toFixed(0);
}
</script>
<style lang="scss" scoped>
.main-contain {
  height: 100%;
  /* background: #fff; */
  width: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
